package com.wzz.seckillone.controller;

import com.alibaba.fastjson.JSON;
import com.wzz.seckillone.pojo.User;
import com.wzz.seckillone.service.UserService;
import com.wzz.seckillone.common.AjaxResult;
import com.wzz.seckillone.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller
@RequestMapping("/login")
@Slf4j
public class LoginController {

    @Autowired
    private UserService userService;





    @GetMapping("/toLogin")
    public String toLogin(){
        return "login";
    }
    @PostMapping("/doLogin1")
    @ResponseBody
    public AjaxResult doLogin1(/*@Valid*/ LoginVo loginVo,HttpServletRequest request,HttpServletResponse response){
        return userService.doLogin(loginVo,request,response);
    }

    /**
     * @Method
     * @Author wzz
     * @Version  1.0
     * @Description加入shiro的登录
     * @param
     * @Return
     * @Exception
     * @Date 2022/3/17 22:20
     */
    @PostMapping("/doLogin")
    @ResponseBody
    public String doLogin(LoginVo loginVo){
        AjaxResult result = new AjaxResult();
        try{
            log.info("doLogin"+loginVo.getMobile()+loginVo.getPassword());
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(loginVo.getMobile(), loginVo.getPassword());
            subject.login(token);
            result.setSuccess(true).setMessage("登录成功");
        }catch(Exception e){
            result.setSuccess(false).setMessage("登陆失败");
        }
        return JSON.toJSONString(result);
    }

    /**
     * @Method
     * @Author wzz
     * @Version  1.0
     * @Description
     * @param
     * @Return
     * @Exception
     * @Date 2022/3/18 14:05
     */
    @GetMapping("/logout")
    public String logout(){
        AjaxResult result = new AjaxResult();
        try{
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            result.setSuccess(true).setMessage("注销成功");
        }catch (Exception e){
            result.setSuccess(false).setMessage("注销失败");
            log.info("注销失败"+e.getMessage());
        }
        return JSON.toJSONString(result);
    }


    @PostMapping("/register")
    public String register(@RequestBody User user, Model model){
        try{
            userService.register(user);
            model.addAttribute("msg","register Success");
        }catch(Exception e){
            model.addAttribute("msg","register Fail");
        }
        return "login";
    }
}
